import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '../views/HomePage.vue'
import LoginView from '../views/Login/LoginView.vue'
import { useUserStore } from '@/stores'
import { jwtDecode } from 'jwt-decode'
import type { JwtPayload } from '@/types/public'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomePage,
      redirect: (to) => {
        const useStore = useUserStore()
        // Check if token exists before trying to decode it
        if (!useStore.token) {
          return '/login'
        }

        try {
          const decode = jwtDecode<JwtPayload>(useStore.token)
          const role = decode['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
          return role === 'Admin' ? '/Admin/chat' : '/User'
        } catch (error) {
          // If token is invalid, redirect to login
          console.error('Invalid token:', error)
          useStore.removeToken() // Clear the invalid token
          return '/login'
        }
      },
      children: [
        {
          path: '/Admin',
          name: 'Admin',
          component: () => import('@/views/Home/AdminPage.vue'),
          redirect: '/Admin/chat',
          // 添加嵌套路由
          children: [
            {
              path: 'chat', // 默认子路由
              component: () => import('@/views/Home/ChatPage.vue'),
            },
            {
              path: 'map', // 保留地图视图路由（需要时可恢复）
              component: () => import('@/views/Home/AdminMap.vue'),
            },
          ],
        },
        {
          path: '/User',
          name: 'User',
          component: () => import('@/views/Home/UserPage.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
  ],
})

// 登录访问拦截 => 默认是直接放行的
// 根据返回值决定，是放行还是拦截
// 返回值：
// 1. undefined / true  直接放行
// 2. false 拦回from的地址页面
// 3. 具体路径 或 路径对象  拦截到对应的地址
//    '/login'   { name: 'login' }
router.beforeEach((to) => {
  // 如果没有token, 且访问的是非登录页，拦截到登录，其他情况正常放行
  const useStore = useUserStore()
  if (!useStore.token && to.path !== '/login') return '/login'
})

export default router
